<?php

namespace api\behaviors;

use common\helpers\CommonHelper;
use Yii;
use yii\base\Behavior;

/**
 * Class BeforeSend
 * @package common\behaviors
 *
 */
class ApiBeforeSend extends Behavior
{
    /**
     * {@inheritdoc}
     */
    public function events()
    {
        return [
            'beforeSend' => 'beforeSend',
        ];
    }

    /**
     * 格式化返回
     *
     * @param $event
     * @throws \Exception
     */
    public function beforeSend($event)
    {
        if (YII_DEBUG && isset(Yii::$app->controller->module->id) && (Yii::$app->controller->module->id === "debug" || Yii::$app->controller->module->id === "gii")) {
            return;
        }

        $response = $event->sender;
        $response->data = [
            'code' => $response->statusCode,
            'message' => $response->statusText,
            'data' => $response->data,
        ];

        //   option 不记录日志
        $is_option = false;

        if(Yii::$app->request->isOptions){
            $is_option = true;
        }

        if (!$is_option) {
            // 记录日志
            $errData = Yii::$app->services->log->record($response, true);
        }

        // 记录登录/登出日志
        $url = CommonHelper::getUrl();
//        if ($url == 'v1/site/login') {
//            Yii::$app->services->logService->loginLog(['login_type' => LoginLog::TYPE_LOGIN],LoginLog::TYPE_GROUP_PC);
//        } elseif ($url == 'v1/site/logout') {
//            Yii::$app->services->logService->loginLog(['login_type' => LoginLog::TYPE_OUT],LoginLog::TYPE_GROUP_PC);
//        } elseif ($url == '/v1/site/ding-login') { // 京港桌面登录 记录登录日志
//            Yii::$app->services->logService->loginLog(['login_type' => LoginLog::TYPE_LOGIN],LoginLog::TYPE_group_JGZM);
//        } elseif ($url == '/dingtalk/site/login-plan') { // 月计划 记录登录日志
//            Yii::$app->services->logService->loginLog(['login_type' => LoginLog::TYPE_LOGIN],LoginLog::TYPE_group_plan);
//        }
//
//        Yii::$app->services->logService->addCommonLogQueue();
        // get不加锁
//        if (Yii::$app->request->isPost) {
            // 去除api 锁
//            $projectId = Yii::$app->params['project_id'] ?? 0;
//            $member_id = Yii::$app->user->identity->member_id ?? 0;
//            $key = 'dengta-'.$projectId.'-'.$member_id.'-'.$url;
//            Yii::$app->services->commonservice->release_global_lock($key);
//        }

        // 格式化报错输入格式
        if ($response->statusCode >= 500) {
            $response->data['data'] = YII_DEBUG ? $errData : '内部服务器错误,请联系管理员!';
        }

        // 提取系统 300-499 的报错信息
        if ($response->statusCode >= 300 && $response->statusCode <= 499) {
            if (isset($response->data['data']['message']) && isset($response->data['data']['status'])) {
                $response->data['message'] = $response->data['data']['message'];
            }

            if (isset($errData['errorMessage'])) {
                $response->data['message'] = $errData['errorMessage'];
                $response->data['message'] == $response->data['data'] && $response->data['data'] = [];
            }
        }

        // 加入ip黑名单
//        $response->statusCode == 429 && Yii::$app->services->ipBlacklist->create(Yii::$app->request->userIP, '请求频率过高');

        $response->format = yii\web\Response::FORMAT_JSON;
        $response->statusCode = 200; // 考虑到了某些前端必须返回成功操作，所以这里可以设置为都返回200的状态码
    }
}